package com.baylor.activity;

import com.baylor.utils.QuitOperateUtil;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.XMPPException;

import com.baylor.R;
import com.baylor.widget.HeaderBarView;
import com.baylor.xmpp.listener.TextChatManagerListener;
import com.xutils.XmppUtils;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {
	
	private HeaderBarView mHeadBarView;

	private XmppUtils mXmppUtils;
	
	private Chat mChat;
	private TextChatManagerListener mChatManagerListener;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        findView();
        initHeaderBar();
        init();
        
    }
    
    @Override
	protected void onDestroy() {
		super.onDestroy();
		
		mXmppUtils.getXmppConnection().getChatManager().removeChatListener(mChatManagerListener);
        mXmppUtils.logout();
	}

    @Override
    public void onBackPressed() {
        // 连续点击两次退出程序
        QuitOperateUtil.quitProgram(this);
    }
    
    // 建一个chat
    public void onCreateChat(View v) {
    	mChat = mXmppUtils.getFriendChat("admin1", null);
    }
    
    // 发送消息
    public void onSendMsg(View v) {
    	try {
			String msgjson = "Hello";
			mChat.sendMessage(msgjson);
		} catch (XMPPException e) {
			Log.d("message", "message 发送失败");
			e.printStackTrace();
		}
    }

    
    //////////////////////////////////////////////////////////////////////////////////////
	private void findView() {
    	mHeadBarView = (HeaderBarView) findViewById(R.id.headBarView);
    }
    
    private void initHeaderBar() {
    	mHeadBarView.setTitle("首页");
    }
    
    private void init() {
    	mXmppUtils = XmppUtils.getInstance();
    	
    	mChatManagerListener = new TextChatManagerListener();
    	mXmppUtils.getXmppConnection().getChatManager().addChatListener( mChatManagerListener );
    }

}
